// 文件操作对话框组件

import React, { useState, useEffect, useRef } from 'react';
import { X, AlertTriangle, CheckCircle, XCircle } from 'lucide-react';
import { FileItem } from '../types/filesystem';

interface FileOperationDialogProps {
  isOpen: boolean;
  onClose: () => void;
  operation: 'create-file' | 'create-folder' | 'rename' | 'delete';
  targetFile?: FileItem;
  parentPath?: string;
  onConfirm: (data: { name?: string; path?: string }) => Promise<boolean>;
}

/**
 * 文件操作对话框组件
 */
export const FileOperationDialog: React.FC<FileOperationDialogProps> = ({
  isOpen,
  onClose,
  operation,
  targetFile,
  parentPath,
  onConfirm,
}) => {
  const [inputValue, setInputValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  
  const inputRef = useRef<HTMLInputElement>(null);

  // 重置状态
  useEffect(() => {
    if (isOpen) {
      setError(null);
      setSuccess(false);
      setIsLoading(false);
      
      // 设置初始值
      if (operation === 'rename' && targetFile) {
        setInputValue(targetFile.name);
      } else {
        setInputValue('');
      }
      
      // 聚焦输入框
      setTimeout(() => {
        inputRef.current?.focus();
        if (operation === 'rename' && targetFile) {
          // 选中文件名（不包括扩展名）
          const dotIndex = targetFile.name.lastIndexOf('.');
          if (dotIndex > 0) {
            inputRef.current?.setSelectionRange(0, dotIndex);
          } else {
            inputRef.current?.select();
          }
        }
      }, 100);
    }
  }, [isOpen, operation, targetFile]);

  // 获取对话框标题
  const getTitle = (): string => {
    switch (operation) {
      case 'create-file':
        return '新建文件';
      case 'create-folder':
        return '新建文件夹';
      case 'rename':
        return '重命名';
      case 'delete':
        return '删除确认';
      default:
        return '文件操作';
    }
  };

  // 获取提示文本
  const getPromptText = (): string => {
    switch (operation) {
      case 'create-file':
        return '请输入文件名:';
      case 'create-folder':
        return '请输入文件夹名:';
      case 'rename':
        return '请输入新名称:';
      case 'delete':
        return `确定要删除 "${targetFile?.name}" 吗？${targetFile?.is_directory ? '此操作将删除文件夹及其所有内容。' : ''}`;
      default:
        return '';
    }
  };

  // 验证输入
  const validateInput = (): string | null => {
    if (operation === 'delete') {
      return null; // 删除操作不需要验证输入
    }

    if (!inputValue.trim()) {
      return '名称不能为空';
    }

    // 检查非法字符
    const invalidChars = /[<>:"/\\|?*]/;
    if (invalidChars.test(inputValue)) {
      return '名称包含非法字符';
    }

    // 检查保留名称
    const reservedNames = ['CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9', 'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9'];
    if (reservedNames.includes(inputValue.toUpperCase())) {
      return '不能使用系统保留名称';
    }

    return null;
  };

  // 处理确认
  const handleConfirm = async () => {
    const validationError = validateInput();
    if (validationError) {
      setError(validationError);
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      let confirmData: { name?: string; path?: string } = {};

      switch (operation) {
        case 'create-file':
        case 'create-folder':
          confirmData = {
            name: inputValue.trim(),
            path: parentPath ? `${parentPath}/${inputValue.trim()}` : inputValue.trim(),
          };
          break;
        case 'rename':
          confirmData = {
            name: inputValue.trim(),
            path: targetFile?.path,
          };
          break;
        case 'delete':
          confirmData = {
            path: targetFile?.path,
          };
          break;
      }

      const success = await onConfirm(confirmData);
      
      if (success) {
        setSuccess(true);
        setTimeout(() => {
          onClose();
        }, 1000);
      } else {
        setError('操作失败');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '操作失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 处理键盘事件
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !isLoading) {
      handleConfirm();
    } else if (e.key === 'Escape') {
      onClose();
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* 背景遮罩 */}
      <div 
        className="absolute inset-0 bg-black bg-opacity-50"
        onClick={onClose}
      />
      
      {/* 对话框 */}
      <div className="relative bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md mx-4">
        {/* 标题栏 */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
            {getTitle()}
          </h3>
          <button
            onClick={onClose}
            className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
            disabled={isLoading}
          >
            <X size={20} />
          </button>
        </div>

        {/* 内容 */}
        <div className="p-4">
          <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
            {getPromptText()}
          </p>

          {/* 输入框（非删除操作） */}
          {operation !== 'delete' && (
            <input
              ref={inputRef}
              type="text"
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyDown={handleKeyDown}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              placeholder={operation === 'create-file' ? '文件名.txt' : '文件夹名'}
              disabled={isLoading}
            />
          )}

          {/* 错误信息 */}
          {error && (
            <div className="mt-3 flex items-center text-red-600 text-sm">
              <XCircle size={16} className="mr-2" />
              {error}
            </div>
          )}

          {/* 成功信息 */}
          {success && (
            <div className="mt-3 flex items-center text-green-600 text-sm">
              <CheckCircle size={16} className="mr-2" />
              操作成功
            </div>
          )}

          {/* 警告信息（删除操作） */}
          {operation === 'delete' && (
            <div className="mt-3 flex items-center text-yellow-600 text-sm">
              <AlertTriangle size={16} className="mr-2" />
              此操作不可撤销
            </div>
          )}
        </div>

        {/* 按钮栏 */}
        <div className="flex items-center justify-end space-x-3 p-4 border-t border-gray-200 dark:border-gray-700">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md"
            disabled={isLoading}
          >
            取消
          </button>
          <button
            onClick={handleConfirm}
            className={`px-4 py-2 text-sm font-medium text-white rounded-md ${
              operation === 'delete'
                ? 'bg-red-600 hover:bg-red-700'
                : 'bg-blue-600 hover:bg-blue-700'
            } disabled:opacity-50 disabled:cursor-not-allowed`}
            disabled={isLoading || success}
          >
            {isLoading ? '处理中...' : operation === 'delete' ? '删除' : '确认'}
          </button>
        </div>
      </div>
    </div>
  );
};
